//jQuery 扩展
jQuery.fn.extend({
    scrolling: function(options, func) {
        var defaults = {
            target: 1,
            timer: 1000,
            offset: 0
        };
        func = func || $.noop;
        var o = jQuery.extend(defaults, options || {});
        this.each(function(i) {
            switch (o.target) {
                case 1:
                    var targetTop = jQuery(this).offset().top + o.offset;
                    jQuery("body").animate({
                        scrollTop: targetTop
                    }, o.timer);
                    break;
                case 2:
                    var targetLeft = jQuery(this).offset().left + o.offset;
                    jQuery("body").animate({
                        scrollLeft: targetLeft
                    }, o.timer);
                    break;
            }
            return false;
        });
        return this;
    }
});
var KS = {
    obj: {},
    tools: {
        in_array: function(value, array) {
            //判断是否在数组中
            var i;
            for (i = 0; i < array.length; i++) {
                if (value === array[i]) {
                    return i;
                }
            }
            return false;
        },
        string: {
            //字符串操作
            format: function() {
                if (arguments.length == 0)
                    return "";
                var args = arguments;
                var str = args[0];
                return str.replace(/\{(\d+)\}/gm, function() {
                    return args[parseInt(arguments[1]) + 1];
                });
            },
            length: function(str) {
                var len = 0;
                for (var i = 0; i < str.length; i++) {
                    if (str.charCodeAt(i) >= 0x4e00 && str.charCodeAt(i) <= 0x9fa5) {
                        len += 2;
                    } else {
                        len++;
                    }
                }
                return len;
            }
        },
        bgflash: function(obj) {
            KS.times = KS.times == undefined ? 1 : KS.times;
            if (KS.times > 2) {
                KS.times = 1;
                return false;
            }
            obj.css({
                background: "#ffc8c8"
            }).addClass("Validform_error");
            setTimeout(function() {
                obj.css({
                    background: "#ffffff"
                }).focus();
                KS.times++;
                setTimeout(function() {
                    KS.tools.bgflash(obj);
                }, 200);
            }, 200);
            return false;
        },
        hashString: function(item) {
            //获取中的地址参数
            if (!item)
                return location.hash.substring(1);
            var sValue = location.hash.match(new RegExp("[\#\&]" + item + "=([^\&]*)(\&?)", "i"));
            sValue = sValue ? sValue[1] : "";
            return sValue == location.hash.substring(1) ? "" : sValue == undefined ? location.hash.substring(1) : decodeURIComponent(sValue);
        },
        cookie: function(name, value, options) {
            //COOKIE操作
            if (typeof value != 'undefined') {
                options = options || {};
                if (value === null) {
                    value = '';
                    $.extend({}, options);
                    options.expires = -1;
                }
                var expires = '';
                if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                    var date;
                    if (typeof options.expires == 'number') {
                        date = new Date();
                        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                    } else {
                        date = options.expires;
                    }
                    expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
                }
                var path = options.path ? '; path=' + (options.path) : '';
                var domain = options.domain ? '; domain=' + (options.domain) : '';
                var secure = options.secure ? '; secure' : '';
                document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
            } else {
                var cookieValue = '';
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = cookies[i].trim();
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
        }
    },
    common: {
        module: [],
        isload: function(module) {
            for (var i in KS.common.module) {
                if (module == KS.common.module[i]) {
                    return true;
                }
            }
            return false;
        },
        load: function(module, callback, alwayscallback) {
            if ($.isArray(module)) {
                for (var i = 0; i < module.length; i++) {
                    $.getScript(module[i], function() {
                        if (i == module.length) {
                            if (typeof callback == 'function') {
                                callback.call();
                            }
                        }
                    });
                }
            } else {
                module = module.replace(/_/g, '.');
                try {
                    if (eval("typeof KS." + module) == 'function') {
                        if (!KS.common.isload(module)) {
                            KS.common.module.push(module);
                            eval("KS." + module + "();");
                            if (typeof callback == 'function') {
                                callback.call();
                            }
                        }
                    }
                } catch (error) {
                    console.log(error);
                }
            }
            if (typeof alwayscallback == 'function') {
                $(function() {
                    alwayscallback.call();
                });
            }
        },
        init: function() {
            $("a.close").live("click", function() {
                $(this).closest(".alert").slideUp();
                return false;
            });

        },
        validform: function(domid, callback) {
            var o = $(domid);
            $("[datatype]", o).each(function() {
                var text = $(this).attr("tipmsg");
                text = text != undefined ? text : "";
                var classname = text != '' ? 'img img_info_t' : '';
                var dd = $(this).closest("dd");
                if (dd.find(".Validform_checktip").size() == 0) {
                    dd.append($('<div class="Validform_checktip"><span class="' + classname + '">&nbsp;</span><b>' + text + '</b></div>'));
                }
            });
            //表单绑定验证事件
            KS.validform = $(".validform", o).Validform({
                btnSubmit: ".submit",
                btnReset: ".reset",
                tiptype: tiptype,
                ignoreHidden: true,
                ajaxPost: true,
                postonce: true,
                datatype: {
                    "notequal": function(gets, obj, curform, regxp) {
                        //参数gets是获取到的表单元素值，obj为当前表单元素，curform为当前验证的表单，regxp为内置的一些正则表达式的引用;
                        if (gets == $("#" + $(obj).attr("notequal")).val()) {
                            return false;
                        } else {
                            return true;
                        }
                        //注意return可以返回true 或 false 或 字符串文字，true表示验证通过，返回字符串表示验证失败，字符串作为错误提示显示，返回false则用errmsg或默认的错误提示;
                    }
                },
                beforeCheck: function(obj) {
                },
                beforeSubmit: function(obj) {
                    $(".alert[rel='error']", obj).remove();
                    //增加loading状态
                    $(".submit b.icon-ok", obj).addClass("icon-loading");
                },
                callback: function(formobj, formret) {
                    console.log(formobj, formret);
                    if (formret.status != undefined) {
                        if (formret.status == 'y') {
                            //验证通过回调事件
                            KS.common.ajaxsuccess(formobj, formret, callback);
                        } else {
                            $(".poststate em", formobj).addClass("img img_error_t");
                            $(".poststate b", formobj).text(formret.info);
                            $(".poststate", formobj).show();
                        }
                    } else {
                        $(".poststate em", formobj).addClass("img img_error_t");
                        $(".poststate b", formobj).text("操作失败！请重试或刷新页面再试！");
                        $(".poststate", formobj).show();
                    }
                }
            });
        },
        ajaxsuccess: function(formobj, formret, callback) {
            if (formret.close != undefined) {
                close = fromret.close;
            } else {
                close = close == 'true' || close == '1' ? true : false;
            }
            //移除按钮上的loading小图标
            $(".submit b.icon-ok", formobj).removeClass("icon-loading");
            //提示成功
            KS.common.suggest("操作成功！");
            //成功状态文本
            var text = formret.info != '' ? formret.info : "操作成功！请关闭或继续操作！";
            $(".poststate em", formobj).removeClass('img_error_t').addClass("img img_success_t");
            $(".poststate b", formobj).text(text);
            $(".poststate", formobj).show();
            //重置表单的元素状态和提示状态
            $(".Validform_checktip span", formobj).removeClass();
            $(".Validform_checktip b", formobj).text('');
            $(".xheditor").html('');
            //判断回调函数并回调
            if (typeof callback == 'function') {
                callback(formobj, formret);
            }
            //重置文本框和状态
            KS.validform.resetForm(formobj);
            //5秒后自动隐藏成功状态文本
            setTimeout(function() {
                $(".poststate").fadeOut(100, function() {
                    $("em", this).removeClass();
                    $("b", this).text('');
                });
            }, 5000);
        },
        suggest: function(text) {
            var bTop = $(document).scrollTop();
            $("#suggest").stop().remove();
            $('<div id="suggest"></div>').appendTo(document.body);
            $("#suggest").html(text).css("left", $(window).width() / 2 - 230 / 2).show().stop(true, true).css({
                "top": ($(window).height() - 31) / 4 * 3 + bTop,
                "opacity": 0.1
            }).animate({
                "opacity": 1,
                "top": $("#suggest").position().top - 30
            }, 800, function() {
                $("#suggest").delay(1200).animate({
                    "opacity": 0.1,
                    "top": $("#suggest").position().top - 30
                }, 1200, function() {
                    $("#suggest").remove();
                });
            });
        }
    },
    loading: function(state) {
        if (state) {
            $("#loading").css("left", $(window).width() / 2 - 36).show();
        } else {
            $("#loading").hide();
        }
    },
    tabs: function(obj, cobj) {
        obj = obj == undefined ? $(".tabs_t") : $(obj);
        //普通选项卡切换
        obj.each(function() {
            var _this = this;
            if (!$(this).hasClass("tabs_n")) {
                $("ul:eq(0)>li", this).live("hover", function() {
                    var _class = this.className.split(" ");
                    if ($.inArray("none", _class) == -1 && $.inArray("more", _class) == -1) {
                        var _index = $(this).parent().children(":not(.more,.none)").index($(this).addClass("current").siblings().removeClass("current").end()[0]);
                        //var tab_content = $(obj).siblings(cobj);//取消同级参考
                        var tabs_c = cobj == undefined ? $(_this).next(".tabs_b").find(".tabs_c") : $(cobj);
                        if (tabs_c.length > 0)
                            tabs_c.hide().eq(_index).show();
                    }
                });
            }
        });
    },
    tips: function(text, options) {
        options = options || {};
        var opt = {
            container: document.body,
            id: '',
            icon: 'normal',
            left: 0,
            top: 0,
            arrow: 'up',
            loc: 20,
            always: false,
            linktext: '我知道了',
            closebtn: true,
            callback: false
        };
        opt = $.extend(opt, options);
        var id = opt.id == '' ? "tips_" + opt.left + '_' + opt.top + '_' + opt.arrow + '_' + opt.loc : opt.id;
        if (opt.always || KS.tools.cookie('close_' + id) != 1) {
            if ($("#" + id).size() > 0) {
                $("#" + id + ".tipstxt .black").html(text);
                $("#" + id).show();
            }
            else {
                var c = '<div id="' + id + '" class="newtips" style="top: ' + opt.top + 'px; left: ' + opt.left + 'px; ">';
                c = c + '<div class="tipcontainer" style="opacity: 1; ">';
                c = opt.arrow == 'up' ? c + '<span class="arrowup" style="margin-left: ' + opt.loc + 'px; "></span>' : c;
                c = opt.arrow == 'left' ? c + '<span class="arrowleft" style="margin-top: ' + opt.loc + 'px; "></span>' : c;
                c = c + '<div class="t_container t_' + opt.arrow + '"><div class="tcc"><div class="t_content"' + (opt.linktext == '' ? ' style="padding-bottom:15px;"' : '') + '>';
                c = opt.icon != '' ? c + '<div class="tipsicon"><span class="tipsico tipsico_' + opt.icon + '"></span></div>' : c;
                c = opt.closebtn ? c + '<a href="javascript:;" class="t_close t_btnclose"></a>' : c;
                c = c + '<div class="tipstxt' + (opt.icon == '' ? " tipsnoicon" : "") + '"><span class="black">' + text + '</span></div>';
                c = opt.linktext != '' ? c + '<div class="tipsrightpanel"><div class="opertbar"><a class="t_close" href="javascript:;">' + opt.linktext + '</a></div></div>' : c;
                c = c + '<div class="clear"></div>';
                c = c + '</div></div></div>';
                c = opt.arrow == 'down' ? c + '<span class="arrowdown" style="margin-left: ' + opt.loc + 'px; "></span>' : c;
                c = opt.arrow == 'right' ? c + '<span class="arrowright" style="margin-top: ' + opt.loc + 'px; "></span>' : c;
                c = c + '</div></div>';
                $(c).appendTo(opt.container);
            }
            $("#" + id + " .t_close").live("click", function() {
                //关闭层和写Cookie
                $("#" + id).fadeOut();
                if (!opt.always) {
                    KS.tools.cookie('close_' + id, 1, {
                        path: '/',
                        expires: 86400
                    });
                }
                if (opt.callback) {
                    opt.callback();
                }
            });
        }
    },
    statistics: {
        expense: function() {
            $(".selspan a[s][e], .staticsdatefilter a[s][e]").live("click", function() {
                $("input[name=charttitle]").val($(this).attr("title"));
                $(".selspan a.btn_g_s").removeClass("btn_g_s").addClass("btn_w_s");
                $(this).addClass("btn_g_s").removeClass("btn_w_s");
                var s = new Date(parseInt($(this).attr("s")) * 1000);
                var e = new Date(parseInt($(this).attr("e")) * 1000);
                $("#startdate").val(s.getFullYear() + "-" + pad((s.getMonth() + 1), 2) + "-" + pad(s.getDate(), 2));
                $("#enddate").val(e.getFullYear() + "-" + pad((e.getMonth() + 1), 2) + "-" + pad(e.getDate(), 2));
                loadchart();
            });

            $(".op_chart .datepicker").live("click", function() {
                $("input[name=charttitle]").val("指定日期");
                $(".selspan a.btn_g_s").removeClass("btn_g_s").addClass("btn_w_s");
            }).live("change", function() {
                loadchart();
            });
        }
    },
    note: {
        index: function() {
        }
    },
    table: {
    },
    user: {
        info: {
        },
        form: function() {
            $(".userform").submit(function(e) {
                e.preventDefault();
                $(".btn_user_form").click();
            });
            $(".btn_user_form").live("click", function() {
                var form = $(this).closest("form");
                form.unbind("submit");
                KS.loading(true);
                $.ajax({
                    type: 'post',
                    url: form.attr("action"),
                    data: form.serialize(),
                    dataType: 'json',
                    success: function(ret) {
                        KS.common.suggest(ret.result);
                        if (ret.code == 1) {
                            location.href = "/mobile/user/";
                        }
                        KS.loading(false);
                    },
                    error: function(ret) {
                        KS.loading(false);
                        KS.common.suggest("失败,请重试");
                    }
                });
                return false;
            });
        },
    },
    config: {
    },
    dialog: {
    },
    bill: {
        edit: function() {
            $("#billform input[name='row[type]']").live("click", function() {
                $("#billform select[id^='category_list_']").attr("name", "").attr("ignore", "ignore").hide();
                $("#billform #category_list_" + $(this).val()).attr("name", "row[category_id]").removeAttr("ignore").show();
                if ($("#billform form").attr("rel") == 'add') {
                    $("#billform form").attr("action", "/bill/" + $("#billform form").attr("rel") + "/" + $(this).val() + "/");
                }
            });
        }
    },
    diary: {
        index: function() {
            $(".star").live("click", function() {
                KS.loading(true);
                var _this = this;
                $.ajax({
                    url: $(this).attr("surl"),
                    dataType: 'json',
                    success: function(ret) {
                        if (ret.code != undefined) {
                            if (ret.code == 0) {
                                if (ret.result == 1) {
                                    $(_this).addClass("star_current");
                                } else {
                                    $(_this).removeClass("star_current");
                                }
                            } else {
                                $.dialog.alert(ret.result);
                            }
                        }
                    },
                    complete: function(ret) {
                        KS.loading(false);
                    }
                });
            });
        }
    },
    budget: {
        index: function() {
            $("#budget_inner>dl>dd>.lp-loading").click(function() {
                if ($.browser.msie && $.browser.version < 8.0) {

                } else {
                    if ($(this).next().css("display") == 'none') {
                        $(".percentage", $(this).next()).each(function() {
                            $(this).easyPieChart({
                                animate: 1000,
                                trackColor: "#e3e3e3",
                                barColor: $(this).attr("data-color")
                            });
                        });
                    }
                }
                $(this).next(".budget_inner_i").slideToggle();
            });
        },
        show: function() {
            $('#budget_inner dl dd:first .percentage').each(function() {
                if ($.browser.msie && $.browser.version < 8.0) {

                } else {
                    $(this).easyPieChart({
                        animate: 1000,
                        trackColor: "#e3e3e3",
                        barColor: $(this).attr("data-color")
                    });
                }
            });
            $("#budget_inner dl dd .load").each(function() {
                $(this).animate({'width': $(this).attr("rel")}, 1000);
            });
        }
    },
    bbs: {
        index: function() {

        },
        show: function() {
            //发表评论
            $("#normalreply").live("submit", function() {
                var _this = this;
                var content = $("textarea[name=content]", this);
                if (content.val() == '') {
                    KS.tools.bgflash(content);
                } else {
                    //避免重复点击产生多次请求事件
                    if ($(_this).attr("posted") == 'true') {
                        return false;
                    } else {
                        $(_this).attr("posted", true);
                    }
                    KS.loading(true);
                    $(".btn_g_s b.icon", _this).addClass("icon-loading");
                    $.ajax({
                        url: $(this).attr("action"),
                        data: $(this).serialize(),
                        type: 'post',
                        success: function(ret) {
                            reply_callback();
                            $(".btn_w_s", _this).click();
                        },
                        error: function(ret) {
                            $.dialog.alert($(ret.responseText).text());
                        },
                        complete: function(ret) {
                            $(".btn_g_s b.icon", _this).removeClass("icon-loading");
                            KS.loading(false);
                            $(_this).removeAttr("posted");
                        }
                    });
                }
                return false;
            });
        }
    },
    family: {
    },
    category: {
    },
    account: {
    },
    task: {
    },
    pjax: {
        init: function() {
            //支持pjax的话使用,不支持的话使用AJAX处理
            if ($.pjax.util.support.pjax) {
                $('#primary').bind('pjax.start', function() {
                    KS.loading(true);
                });
                $('#primary').bind('pjax.end', function(ret) {
                    KS.loading(false);
                });
                $.pjax({
                    selector: '.ajax[href]:not([output]),.ajax:not([output]) a[href][class!=dialog]', //匹配的元素
                    container: '#primary', //内容替换的容器
                    show: '', //展现的动画
                    cache: false, //是否使用缓存
                    storage: true, //是否使用本地存储
                    titleSuffix: ' - 记账家', //标题后缀
                    filter: function() {
                        var url = $(this).attr("href");
                        if (url.substr(0, 10) == 'javascript' || url == '')
                            return true;
                    },
                    callback: function() {
                    }
                });
                obj = ".ajax[href][output],.ajax[output] a";
            } else {
                obj = ".ajax[href],.ajax a[href][class!=dialog]";
            }
            $(obj).live("click", function() {
                var _this = this;
                var url = $(this).attr("href");
                if (url == undefined)
                    return false;
                var output = $(this).attr("output");
                if (output == undefined) {
                    output = $(this).parent().attr("output");
                    if (output == undefined) {
                        output = '#primary';
                    }
                }
                if (url.substr(0, 10) == 'javascript' || url == '')
                    return false;
                KS.loading(true);
                $.ajax({
                    url: url,
                    success: function(ret) {
                        if (ret.substr(0, 1) == '{') {
                            eval("var obj = " + ret + ";");
                            if (obj != undefined && obj.result != undefined) {
                                $.dialog.alert(obj.result);
                            }
                        } else {
                            $(output).html(ret);
                            if (!$(_this).parent().parent().parent().hasClass('tabs_t')) {
                                $(output).scrolling({
                                    timer: 0,
                                    offset: -40
                                });
                            }
                        }
                    },
                    error: function(ret) {
                        $.dialog.alert($(ret.responseText).find("h1").text());
                    },
                    complete: function(ret) {
                        KS.loading(false);
                    }
                });
                return false;
            });
        }
    }
};

function tiptype(msg, o, cssctl) {
    //msg：提示信息;
    //o:{obj:*,type:*,curform:*}, obj指向的是当前验证的表单元素（或表单对象），
    //type指示提示的状态，值为1、2、3、4， 1：正在检测/提交数据，2：通过验证，3：验证失败，4：提示ignore状态, curform为当前form对象;
    //cssctl:内置的提示信息样式控制函数，该函数需传入两个参数：显示提示信息的对象 和 当前提示的状态（既形参o中的type）;
    //验证表单元素时o.obj为该表单元素，全部验证通过提交表单时o.obj为该表单对象;
    if (!o.obj.is("form")) {
        var objtip = o.obj.siblings(".Validform_checktip");
        //cssctl(objtip,o.type);
        cssstyle(objtip, o.type);
        msg = o.type == 1 || o.type == 2 ? '' : msg;
        objtip.find("b").html(msg);
    } else {
        if (o.type == 3) {
            $(".submit b.icon-ok", o.obj).removeClass("icon-loading");
            $(".col_box", o.obj).prepend("<div class='alert alert_block' rel='error'>提交数据失败！请注意保存数据然后刷新重试！</div>")
        }
    }
}
//validform表单验证样式
function cssstyle(obj, status) {
    obj = obj.find("span");
    obj.removeClass("img_info_t");
    switch (status) {
        case 1:
            obj.removeClass("img_success_t img_error_t").addClass("img img_loading");//checking;
            break;
        case 2:
            obj.removeClass("img_error_t img_loading").addClass("img img_success_t");//passed;
            break;
        case 4:
            obj.removeClass("img_success_t img_error_t img_loading").addClass("img img_warning_t");//for ignore;
            break;
        default:
            obj.removeClass("img_success_t img_loading").addClass("img img_error_t");//wrong;
    }
}
function loadchart() {
    $.ajax({
        url: "/statics/expense",
        type: 'POST',
        dataType: 'html',
        data: $("#expenseform").serialize(),
        success: function(ret) {
            $("#expensechart").html(ret);
        }
    });
}
/* 查表法(完善版本)  by aimingoo */
pad = function(tbl) {
    return function(num, n) {
        return (0 >= (n = n - num.toString().length)) ? num : (tbl[n] || (tbl[n] = Array(n + 1).join(0))) + num;
    }
}([]);
$(function() {
    KS.common.init();//通用
    KS.tabs();//选项卡
    KS.pjax.init();//PJAX
    //console.log('done@' + new Date().getHours() + ":" + new Date().getMinutes() + ":" + new Date().getSeconds());
});